package com.qianbei.user.regist;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.android.volley.RequestQueue;
import com.android.volley.ext.HttpCallback;
import com.android.volley.ext.RequestInfo;
import com.qianbei.R;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.utilis.Permission;
import com.qianbei.common.utilis.Util;
import com.qianbei.common.utilis.img.CanmlTools;
import com.qianbei.common.utilis.img.CanmlTools.CamerCallback;
import com.qianbei.common.utilis.img.ImageTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class ImproveDataActivity extends BaseActivity implements CamerCallback {

	private EditText mNameEdit, mCountryEdit, mCityEdit,mIntroduceEdit;

	private ImageView impro_nan, impro_nv, change_icon;

	private String sexString = "1";// 1男 0女

	private CanmlTools canmlTools = null;

	private String imgData;
	private RequestQueue mQueue;

	private ProgressDialog d;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.improvdata_activity);
		d = new ProgressDialog(mContext);
	}

	@Override
	public void initView() {
		change_icon = (ImageView) findViewById(R.id.chang_icon);
		mNameEdit = (EditText) findViewById(R.id.et_name);
		mCityEdit = (EditText) findViewById(R.id.et_city2);
		mCountryEdit = (EditText) findViewById(R.id.country);
		mIntroduceEdit = (EditText) findViewById(R.id.et_introduce);
		impro_nan = (ImageView) findViewById(R.id.impro_nan);
		impro_nv = (ImageView) findViewById(R.id.impro_nv);
	}

	@Override
	public void initClick() {
		setTitle("完善个人资料");
		impro_nv.setOnClickListener(this);
		impro_nan.setOnClickListener(this);
		findViewById(R.id.btn_login).setOnClickListener(this);
		canmlTools = new CanmlTools(mContext, this);
		change_icon.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
//		super.onClick(v);
		switch (v.getId()) {
		case R.id.btn_login:
			Util.hideSoftInputFromWindow(v);
			improvmentData();
			break;
		case R.id.impro_nan:
			sexString = "1";
			impro_nan.setBackgroundResource(R.drawable.aq_ask_name_select);
			impro_nv.setBackgroundResource(R.drawable.aq_ask_name_un);
			break;
		case R.id.impro_nv:
			sexString = "0";
			impro_nan.setBackgroundResource(R.drawable.aq_ask_name_un);
			impro_nv.setBackgroundResource(R.drawable.aq_ask_name_select);
			break;

		case R.id.chang_icon:
//			canmlTools.showCanmel(v.getId(), 2);
			checkPermission(v);
			break;
		default:
			break;
		}
	}

	/**
	 *
	 * android 6.0运行时权限检查
	 *
	 * @param v
	 */
	public void checkPermission(View v){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
			if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
					|| ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
				ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
								Manifest.permission.CAMERA},
						Permission.WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
			}else{
				canmlTools.showCanmel(v.getId(), 2);
			}

		}else {
			canmlTools.showCanmel(v.getId(), 2);
		}

	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);

		if (requestCode == Permission.WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
			if(grantResults.length > 0){

				if (grantResults.length > 1){
					if (grantResults[0] == PackageManager.PERMISSION_GRANTED &&
							grantResults[1] == PackageManager.PERMISSION_GRANTED){
						canmlTools.showCanmel(R.id.perceter_icon, 2);
					}
				}
			}
		}
	}


	/**
	 * 提交用户资料
	 */
	private void improvmentData() {

		String realName = mNameEdit.getText().toString();
		String country = mCountryEdit.getText().toString();
		String city = mCityEdit.getText().toString();
		String career = mIntroduceEdit.getText().toString();


		if(TextUtils.isEmpty(realName)){
			new MsgAlert().show(getString(R.string.empty_name));
			return;
		}

//
//		if(TextUtils.isEmpty(country)){
//			new MsgAlert().show(getString(R.string.empty_country));
//			return;
//		}
//
//		if(TextUtils.isEmpty(city)){
//			new MsgAlert().show(getString(R.string.empty_city));
//			return;
//		}

//		if(TextUtils.isEmpty(identity)){
//			new MsgAlert().show(getString(R.string.empty_post));
//			return;
//		}

//		if(TextUtils.isEmpty(career)){
//			new MsgAlert().show(getString(R.string.empty_introduction));
//			return;
//		}

//		upLoadImage(realName,career,city);

		Map<String, Object> params = new HashMap<String, Object>();

		params.put("user[name]", realName);
		params.put("user[sex]", sexString);
		params.put("user[identity]", "");
		params.put("user[career]", career);
		params.put("user[country]",country);
		params.put("user[city]", city);

		if (imgData != null) {
			params.put("profile_image_url", new File(imgData));
		}
		ServerControl sc = new ServerControl();
		// sc = new ServerControl(URL + "transaction_app/users/update_info",
		// "user[name]", name.getText().toString(), "user[identity]",
		// touxie.getText().toString(), "user[career]", et_introduce
		// .getText().toString());
		RequestInfo requestInfo = new RequestInfo();
		requestInfo.url = updatInfoString;
		requestInfo.putAllParams(params);
		sc.upload(requestInfo, new HttpCallback() {

			@Override
			public void onStart() {
				d.showProgress("正在加载");
			}

			@Override
			public void onResult(String string) {
				try {
					JSONObject jsonObject = new JSONObject(string);
					if (jsonObject.optBoolean("status")) {

						if (!TextUtils.isEmpty(jsonObject.optString("face"))) {
							SetData.setFace(jsonObject.optString("face"));
						}

//						if (SetData.getLoginshow(GlobalConfig.getInstance().userID)) {
//							startActivity(LogginShowActivity.class);
//							SetData.setLoginshow(false,
//									GlobalConfig.getInstance().userID);
//						} else {

//						}
					} else {
						new MsgAlert().show(jsonObject.optString("msg"));
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

			@Override
			public void onLoading(long count, long current) {

			}

			@Override
			public void onFinish() {
				d.close();
			}

			@Override
			public void onError(Exception e) {

			}

			@Override
			public void onCancelled() {

			}
		});
	}

	/**
	 * 上传图片
	 */
	private void upLoadImage(String realName, String career,String city) {


		Map<String, Object> params = new HashMap<String, Object>();
		if (imgData != null) {
			params.put("user[name]", realName);
			params.put("user[sex]", sexString);
			params.put("user[identity]", "");
			params.put("user[career]", career);
			params.put("user[city]", city);

			if (imgData != null) {
				params.put("profile_image_url", new File(imgData));
			}
		}
		ServerControl sr = new ServerControl(updatInfoString,params);
		sr.serverListener = new ServerControl.ServerListener() {
			@Override
			public void serverFinish(ServerResult sr) {

				if (sr.isContinue) {
					if (!TextUtils.isEmpty(sr.bodyData.optString("face"))) {
						SetData.setFace(sr.bodyData.optString("face"));
					}

				} else {
					new MsgAlert().show(sr.bodyData.optString("msg"));
				}
			}
		};

		new ProgressDialog(mContext).startControlUPpic(sr);// .showProgress("正在上传");

	}

	@Override
	public void camerPickphoto(String imageUri, int i) {
		Bitmap tempbBitmap = ImageTools.bitmapFromPath(imageUri,
				(int) ImageTools.getDensity() * 65,
				(int) ImageTools.getDensity() * 65);

		imgData = imageUri;
		change_icon.setImageDrawable(new BitmapDrawable(getResources(),
				tempbBitmap));
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}
		canmlTools.onresult(requestCode, data);
	}


//	@Override
//	// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//			clear();
//		}
//		return super.onKeyDown(keyCode, event);
//	}

//	public void clear(){
//		SetData.setUserID("");
//		SetData.setFace("");
//		SetData.sethxID("");
//		SetData.sethxpass("");
//		SetData.setUserPhone("");
//	}
//
//	@Override
//	public void fClick(int id) {
//		switch (id) {
//			case R.id.title_left2:
//				clear();
//				break;
//			default:
//				break;
//		}
//	}
}
